package com.burybell.storage.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOUtils {

    public static void copy(InputStream inputStream, OutputStream outputStream,long length,int buffer) throws IOException {
        long slice = length / buffer;
        long remain = length - slice * buffer;
        byte[] data = new byte[buffer];
        for (long i = 0; i < slice; i++) {
            int len = inputStream.read(data);
            outputStream.write(data,0,len);
            outputStream.flush();
        }

        byte[] remainData = new byte[Math.toIntExact(remain)];
        int read = inputStream.read(remainData);
        if (read == remain) {
            outputStream.write(remainData,0,read);
            outputStream.flush();
        }
    }

    public static long getDirSize(File file) {
        //判断文件是否存在
        if (file.exists()) {
            //如果是目录则递归计算其内容的总大小
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                long size = 0;
                assert children != null;
                for (File f : children)
                    size += getDirSize(f);
                return size;
            } else {//如果是文件则直接返回其大小,以“兆”为单位
                return file.length();
            }
        } else {
            return -1;
        }
    }

}
